package SingleLinkedList;

import static SingleLinkedList.SmallerEqualBigger.*;

public class MergeTwoOrderList {

    public Node merge(Node head1, Node head2) {
        if (head1 == null || head2 == null) {
            return head1 == null ? head2 : head1;
        }

        Node head = head1.value <= head2.value ? head1 : head2;

        Node cur1 = head.next;
        Node cur2 = head == head1 ? head2 : head1;

        Node pre = head;

        // 有一个链表没有元素就跳出
        while (cur1 != null && cur2 != null) {
            if (cur1.value <= cur2.value) {
                pre.next = cur1;
                cur1 = cur1.next;
            } else {
                pre.next = cur2;
                cur2 = cur2.next;
            }
            pre = pre.next;
        }
        // 另一个链表的尾巴直接接到后面
        pre.next = cur1 != null ? cur1 : cur2;

        return head;
    }
}
